package com.example.servicemodule;


import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class BookManagerService extends Service {
    private static final String TAG = "BookManagerService";

    private CopyOnWriteArrayList<Book> mCopyOnWriteList = new CopyOnWriteArrayList();

    private IBinder mBinder = new IBookManager.Stub() {
        // service可以获取到client传递过来的数据，但是无法对client传递过来的数据进行修改
        // 返回的数据是新的对象
        // 数据的流向是从客户端->服务端
        @Override
        public Book addInBook(Book book) throws RemoteException {
            Log.i(TAG, "addInBook: book" + book);
            book.bookID = -1;
            book.bookName = book.bookName + "-in";
            mCopyOnWriteList.add(book);
            return book;
        }

        // 数据由service传递到client，能修改client端传递过来的数据
        // 数据的流向是服务端到客户端
        @Override
        public Book addOutBook(Book book) throws RemoteException {
            Log.i(TAG, "addOutBook: book" + book.toString());
            book.bookID = -1;
            book.bookName = book.bookName + "-out";
            mCopyOnWriteList.add(book);
            return book;
        }

        @Override
        public Book addInoutBook(Book book) throws RemoteException {
            Log.i(TAG, "addInoutBook: book" + book.toString());
            book.bookID = -1;
            book.bookName = book.bookName + "-inout";
            mCopyOnWriteList.add(book);
            return book;
        }

        @Override
        public List<Book> getBookList() throws RemoteException {
            return mCopyOnWriteList;
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind: ");
        return mBinder;
    }
}
